import { ref, computed } from 'vue';
import {resizeObserverDOM} from "@/utils/rem";

export function useDraggable(initialOffsetX = 0, initialOffsetY = 0) {
    const initialX = ref(0);
    const initialY = ref(0);
    const offsetX = ref(initialOffsetX);
    const offsetY = ref(initialOffsetY);
    const isDragging = ref(false);
    let dragWidth = 0, dragHeight = 0;

    const boxStyle = computed(() => ({
        transform: `translate(${offsetX.value}px, ${offsetY.value}px)`
    }));

    function startDrag(event) {
        isDragging.value = true;

        dragWidth = event.srcElement.clientWidth;
        dragHeight = event.srcElement.clientHeight;
        initialX.value = event.clientX;
        initialY.value = event.clientY;
    }

    function onDrag(event) {
        if (!isDragging.value) return;

        const dx = event.clientX - initialX.value;
        const dy = event.clientY - initialY.value;

        offsetX.value += dx;
        offsetY.value += dy;

        initialX.value = event.clientX;
        initialY.value = event.clientY;
    }

    function stopDrag(event, cb) {
        isDragging.value = false;
        if (cb && (dragWidth !== event.srcElement.clientWidth || dragHeight !== event.srcElement.clientHeight)) {
            cb();
        }
    }

    return {
        boxStyle,
        startDrag,
        onDrag,
        stopDrag,
    };
}
